import 'dart:async';
import 'package:flutter/material.dart';

class CountdownTextSplit extends StatefulWidget {
  final String timeStr; // 如 "23:59:59" 或 "8天:23:59:59"

  const CountdownTextSplit({super.key, required this.timeStr});

  @override
  State<CountdownTextSplit> createState() => _CountdownTextSplitState();
}

class _CountdownTextSplitState extends State<CountdownTextSplit> with AutomaticKeepAliveClientMixin {
  late Duration _duration;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _duration = parseTime(widget.timeStr);
    startCountdown();
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  /// 启动倒计时
  void startCountdown() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (_duration.inSeconds <= 0) {
        timer.cancel();
      } else {
        setState(() {
          _duration -= Duration(seconds: 1);
        });
      }
    });
  }

  /// 解析格式为 “8天:23:59:59” 或 “23:59:59”
  Duration parseTime(String str) {
    int days = 0;
    String timePart = str;

    if (str.contains("天:")) {
      var parts = str.split("天:");
      days = int.tryParse(parts[0]) ?? 0;
      timePart = parts[1]; // 取出“23:59:59”
    }

    var timeParts = timePart.split(":").map((e) => int.tryParse(e) ?? 0).toList();
    int hours = timeParts.length > 0 ? timeParts[0] : 0;
    int minutes = timeParts.length > 1 ? timeParts[1] : 0;
    int seconds = timeParts.length > 2 ? timeParts[2] : 0;

    return Duration(days: days, hours: hours, minutes: minutes, seconds: seconds);
  }

  /// 格式化为 "HH:mm:ss"
  String formatHMS(Duration d) {
    final h = (d.inHours % 24).toString().padLeft(2, '0');
    final m = (d.inMinutes % 60).toString().padLeft(2, '0');
    final s = (d.inSeconds % 60).toString().padLeft(2, '0');
    return '$h:$m:$s';
  }

  @override
  Widget build(BuildContext context) {
    final days = _duration.inDays;

    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        if (days > 0)
          Text(
            '$days 天',
            style: TextStyle(fontSize: 12, color: Colors.white),
          ),
        SizedBox(width: 8),
        Text(
          formatHMS(_duration),
          style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: Colors.white),
        ),
      ],
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
